package demo.spring.securing.manager;

import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Iterator;

/**
 * 权限管理决断器
 * <p>
 * Created by lushun.chen on 2017/4/17.
 *
 * @author lushun.chen
 */
public class CustomAccessDecisionManager implements AccessDecisionManager {

    private static final Logger logger = Logger.getLogger(CustomAccessDecisionManager.class);

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if (collection == null) {
            return;
        }

        //权限角色
        Iterator<ConfigAttribute> iterable = collection.iterator();

        while (iterable.hasNext()) {
            ConfigAttribute configAttribute = iterable.next();
            String needRole = configAttribute.getAttribute();
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needRole.equals(grantedAuthority.getAuthority())) {
                    return;
                }
            }
            logger.info("need role id " + needRole);
        }
        throw new AccessDeniedException("Can not Access!");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
